<template>
  <div id="mapDiv">
    <div class="slot">
      <div class="backs" v-if="show">
        <div class="back-items" @click.stop="addManagement"><i class="el-icon-rank"></i>基地</div>
        <div class="back-items" @click.stop="addLand"><i class="el-icon-film"></i>地块</div>
        <div class="back-items" @click.stop="addCamera"><i class="el-icon-odometer"></i>传感器</div>
        <div class="back-items" @click.stop="tangleTool"><i class="el-icon-menu"></i>矩形地块</div>
      </div>
    </div>
  </div>
</template>
<script>
import {pddm} from './panduan.js'
import MapInit from './mapint.js'
import { findAllCoords } from '../util/api.js'
export default {
  props: {
    show: {
      type: Boolean,
      default: true
    },
    clear: {
      type: Boolean
    }
  },
  data() {
    return {
      map: null,
      lay: null,
      config: {
        showLabel: false,  // 不显示面积信息
        color: "#FFFFFF",
        weight: 3,
        opacity: 0.5,
        fillColor: "#FFFFFF",
        fillOpacity: 0.5
      },
      infoAdd:{
        baseId:"",
        baseName:"",
        coords:[],
      },
      basePolygons:[],
      tables: {},
      handlers: null,
    }
  },
  mounted() {
    this.findAllCoords()
    this.$nextTick(() => {
      this.initTdtMap();
    })

  },
  watch: {
    clear: function (newVal, oldVal) {
      if (newVal) {
        // console.log(this)
        this.handlers.clear()
        this.$emit("clearChange", false)
      }
    },
  },
  methods: {
    async findAllCoords() {
      let res = await findAllCoords()
      //  console.log(res) 
      if (res.code != 200) return
      this.tables = res.data
      this.addPoints(res.data)
    },
    initTdtMap() {
      MapInit.init().then((T) => {
        this.map = new T.Map('mapDiv');
        this.map.centerAndZoom(new T.LngLat(107.721097, 35.125455), 16);
        this.map.disableDoubleClickZoom();
        this.map.setMapType(window.TMAP_HYBRID_MAP);
      })
    },
    //添加摄像头
    addCamera() {   
      var icon = new T.Icon({
                iconUrl: "https://foster-use.oss-cn-chengdu.aliyuncs.com/foster/20231115_a479655c-518a-41.png",
                iconSize: new T.Point(19, 27),
                iconAnchor: new T.Point(10, 25)
      });
      this.handlers = new T.MarkTool(this.map, { follow: true, icon });
      this.handlers.open();
      this.handlers.addEventListener('draw', this.drawFinish)
    },
    //添加摄像头结束
    drawFinish(e) {
      // console.log("顶点坐标列表 ----------> ", e.currentLnglats)
    },
    //添加基地
    addManagement() {
      this.handlers = new T.PolygonTool(this.map, this.config);
      this.handlers.open();
      this.handlers.addEventListener('draw', this.managementFinish)

    },
    //添加基地结束
    managementFinish(e) {
      //   console.log("顶点坐标列表 ----------> ",e.currentLnglats)
      this.$emit("change", e)
    },
    //添加地块
    addLand() {
      //判断是否有基地
      if (this.tables.baseS.length <= 0) return this.$message.error('请先添加基地')
      this.handlers = new T.PolygonTool(this.map, this.config);
      this.handlers.open();
      //判断点位位置是否在一个基地内
      this.handlers.addEventListener('addpoint', this.landReturn);
      //绘制结束
      this.handlers.addEventListener('draw', this.landFinish);
    },
    //判断添加地块过程
    landReturn(e){  
      let point = e.currentLnglats.slice(e.currentLnglats.length - 1)
      let isTrue = false
      point.forEach((pot)=>{
        this.basePolygons.forEach((v)=>{
             if(pddm(pot,v.polygon)){ 
                if(this.infoAdd.baseId&&v.baseId!=this.infoAdd.baseId){ //判断是否在同一个基地
                  this.infoAdd.baseId=""
                  this.infoAdd.baseName=""
                   isTrue = false
                   this.handlers.close()
                }else{
                  isTrue = true
                  this.infoAdd.baseId = v.baseId
                  this.infoAdd.baseName = v.baseName
                }
             }
        })
      })
     if(!isTrue){
        this.$message.error('请添加地块在基地内')
        this.handlers.close()
     }    
    },
    //添加地快绘制结束
    landFinish(e) {
      this.$emit("landChange", { e, data: this.infoAdd })
    },
    //添加标记
    addPoints(arr) {
      let baseS = arr.baseS
      let landS = arr.landS
      let equipmentS = arr.equipmentS
      if(baseS.length>0){
        let center = JSON.parse(baseS[0].baseCoords)[0]
        this.map.centerAndZoom(new T.LngLat(center.lng, center.lat), 17);
      }
      //添加基地
      baseS.forEach((base) => {
        let baseSpoints = [];
        let pointArray = JSON.parse(base.baseCoords)
        pointArray.forEach((item) => {
          baseSpoints.push(new T.LngLat(item.lng, item.lat))
        })
        let data = {
           baseId: base.baseId,
           baseName:base.baseName,
           polygon:pointArray
        }
        this.basePolygons.push(data)
        let polygon = new T.Polygon(baseSpoints, {
          color: base.baseColor, weight: 1, opacity: 1, fillColor: base.baseColor, fillOpacity: 0.5
        });
        this.map.addOverLay(polygon);
        //基地点击
        polygon.addEventListener("click", () => {
          this.$emit('baseClick', base)
        });
      })
      //添加地块
      landS.forEach((base) => {
        let baseSpoints = [];
        let pointArray = JSON.parse(base.landCoords)
        pointArray.forEach((item) => {
          baseSpoints.push(new T.LngLat(item.lng, item.lat))
        })
        let polygon = new T.Polygon(baseSpoints, {
          color: base.landColor, weight: 1, opacity: 1, fillColor: base.landColor, fillOpacity: 0.5
        });
        this.map.addOverLay(polygon);
        //地块点击
        polygon.addEventListener("click", () => {
          this.$emit('landClick', base)
        });
      })
      //添加点位
      equipmentS.forEach((base) => {
        let point = JSON.parse(base.equipmentCoords)
        let icon = new T.Icon({
          iconUrl: base.iconUrl,
          iconSize: new T.Point(26, 26),
        });
        let marker = new T.Marker(new T.LngLat(point[0].lng, point[0].lat), { icon: icon });
        this.map.addOverLay(marker);
        //基地点击
        marker.addEventListener("click", () => {
          this.$emit('equipmentClick', base)
        });
      })

    },
    //传感器
    tangleTool() {
      //判断是否有基地
      // if (this.tables.baseS.length <= 0) return this.$message.error('请先添加基地')
      this.handlers = new T.RectangleTool(this.map, this.config);
      this.handlers.open();
      //判断点位位置是否在一个基地内
      // this.handlers.addEventListener('addpoint', this.landReturn);
      //绘制结束
      this.handlers.addEventListener('draw', this.landFinish);
    },
  }
}
</script>
<style lang="less" scoped>
#mapDiv {
  width: 100%;
  height: 100%;
  position: relative;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  .slot {
    width: 100%;
    z-index: 9999;
    position: absolute;
    top: 0;
    left: 0;

    .backs {
      width: 100%;
      display: flex;
      padding-top: 20px;

      .back-items {
        background-color: #ffffff;
        padding: 10px 40px;
        cursor: pointer;
        margin: 0 20px;
        border-radius: 10px;
        display: flex;
        flex-direction: column;
        align-items: center;
        font-size: 18px;
      }
    }
  }


}
</style>
  